package com.wxy.common.utils;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Data
@SuppressWarnings("unchecked")
public class ValidResult {
    private Integer status;

    private String error;

    private List<ValidError> errors;

    public ValidResult() {
        this.setStatus(200);
        this.setErrors(new ArrayList<>());
    }

    public void fail(String field, String code, String message) {
        this.setStatus(400);
        this.setError("Bad Request");

        ValidError validError = new ValidError();
        validError.setField(field);
        validError.setCode(code);
        validError.setDefaultMessage(message);

        List<ValidError> validErrors = this.getErrors();
        validErrors.add(validError);

        this.setErrors(validErrors);
    }

    public void fail_exists(Object entity, String field, Object existsEntity) {
        String val = this.getFieldValue(entity, field);
        if (val != null && !val.equals("") && existsEntity != null) {
            this.fail(field, "Exists","已存在 " + val);
        }
    }

    public void fail_exists_update(Object entity, String field, Object existsEntity) {
        Long id = this.getFieldValue(entity, "id");
        Long exists_id = this.getFieldValue(existsEntity, "id");
        String val = this.getFieldValue(entity, field);
        if (val != null && !val.equals("") && existsEntity != null && !id.equals(exists_id)) {
            this.fail(field, "Exists","已存在 " + val);
        }
    }

    @JsonIgnore
    public Boolean isPass() {
        return this.getStatus().equals(200);
    }

    private <T> T getFieldValue(Object entity, String key){
        try {
            Class<?> clz = entity.getClass();
            Method m = entity.getClass().getMethod("get" + getMethodName(key));
            T val = (T) m.invoke(entity);
            return val;
        } catch (Exception e) {
            return null;
        }
    }

    private String getMethodName(String fildeName) throws Exception {
        byte[] items = fildeName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return new String(items);
    }
}
